package com.example.covid19.controller;


import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.crypto.SecureUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.covid19.common.Dto.Editdto;
import com.example.covid19.common.Dto.EdpassDto;
import com.example.covid19.common.lang.Result;
import com.example.covid19.entity.*;
import com.example.covid19.mapper.AdministrateurMapper;
import com.example.covid19.mapper.StudentMapper;
import com.example.covid19.service.*;
import com.example.covid19.service.impl.DemanderServiceImpl;
import com.example.covid19.util.ExcelReader;
import com.example.covid19.util.MessageUtil;
import com.example.covid19.util.Rqizhuanhuan;
import com.example.covid19.util.SecretUtil;
import com.example.covid19.util.tencent.Metixing;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.time.LocalDate;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;

import static com.example.covid19.util.SecretUtil.secret;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author BaiZhengChun
 * @since 2023-03-07
 */
@Slf4j
@RestController
@RequestMapping("/administrateur")
public class AdministrateurController {

    private final AdministrateurService administrateurService;
    private final AdministrateurMapper administrateurMapper;
    private final StudentMapper studentMapper;
    private final StudentService studentService;
    private final StudentinfoService studentinfoService;
    private final CheeckService cheeckService;
    private final DemanderServiceImpl DemanderService;
    private final StustatusService stustatusService;
    @Autowired
    Rqizhuanhuan zhuan;
    @Autowired
    Metixing metixing;
    @Autowired
    StationMessageService stationMessageService;
    @Autowired
    ChanbedService chanbedService;
    @Autowired
    MessageUtil messageUtil;

    public AdministrateurController(AdministrateurService administrateurService, AdministrateurMapper administrateurMapper, StudentMapper studentMapper, StudentService studentService, StudentinfoService studentinfoService, CheeckService cheeckService, DemanderServiceImpl DemanderService, StustatusService stustatusService) {
        this.administrateurService = administrateurService;
        this.administrateurMapper = administrateurMapper;
        this.studentMapper = studentMapper;
        this.studentService = studentService;
        this.studentinfoService = studentinfoService;
        this.cheeckService = cheeckService;
        this.DemanderService = DemanderService;
        this.stustatusService = stustatusService;
    }

    /**
     * @return 保存没有打卡的的学生记录student转cheeck, 99行可以单独拎出来一个接口
     * @parm none
     */
    @RequestMapping("/checktostu")
    public Result checktostu() {
        List<Student> studentList = studentService.list(new QueryWrapper<Student>().eq("istrue", 0));
        System.out.println(studentService.list(new QueryWrapper<Student>().eq("istrue", 0)));//这里是给管理员看的
        List<Cheeck> cheeckList = studentList.stream()
                .map(v -> {
                    return new Cheeck(v.getStudentid(), String.valueOf(v.getIstrue()), LocalDate.now(), 0);
                }).collect(Collectors.toList());
        System.out.println(cheeckList);
        return Result.success(200, "成功", cheeckList);
    }

    /**
     * @param
     * @return 管理员查看没有打卡的学生(自己管理的)
     */
    @RequestMapping("/cheek0")
    public Result check0(HttpServletRequest httpServletRequest) {
        String s = (String) StpUtil.getLoginIdByToken(httpServletRequest.getHeader("satoken"));
        return Result.success(200, "yes", administrateurMapper.getcheck0(Integer.valueOf(s)));
    }

    /**
     * 今天没打卡的学生发送短信进行提醒
     */
    @RequestMapping("/sendchecksto")
    public void sendchecksto() {
        List<Student> studentList = studentService.list(new QueryWrapper<Student>().eq("istrue", 0));
        ArrayList<String> stringArrayList = new ArrayList<>();
        studentList.forEach(v -> {
            metixing.sendMessage(v.getPhone());
        });
    }

    /**
     * 设置打卡延长时间
     */
//    @RequestMapping("/addtime")
//    public void addtime(@RequestBody Editdto editdto){
//
//    }

    /**
     * @return 返回没有审批的请假数据
     */
    @RequestMapping("/getdem")
    public Result getdem(HttpServletRequest httpServletRequest) {
        String s = (String) StpUtil.getLoginIdByToken(httpServletRequest.getHeader("satoken"));
        return Result.success(200, "返回", administrateurMapper.qingjiainfo(s));
    }
    /**
     * @return 同意/拒绝换寝请求
     */
    @RequestMapping("/sucgetbed")
    public Result sucgetbed(@RequestBody Editdto editdto) {
        Chanbed chanbed = chanbedService.getOne(new QueryWrapper<Chanbed>().eq("id",editdto.getFacetoken()));
        if (editdto.getBiaoshi()==0){
            chanbed.setIson(1);
            System.out.println("ddsds");
            messageUtil.sendAny(1,chanbed.getRid(), String.valueOf(stustatusService.getOne(new QueryWrapper<Stustatus>().eq("studentid",editdto.getUsername())).getBbid()));
        }else {
            chanbed.setIson(2);
        }
        chanbedService.updateById(chanbed);
        return Result.success(200, "ok",null);
    }

    @RequestMapping("/errdem")
    public Result errdem(HttpServletRequest httpServletRequest) {
        String s = (String) StpUtil.getLoginIdByToken(httpServletRequest.getHeader("satoken"));
        return Result.success(200, "返回", administrateurMapper.errinfo(s));
    }

    @RequestMapping("/sucdem")
    public Result sucdem(HttpServletRequest httpServletRequest) {
        String s = (String) StpUtil.getLoginIdByToken(httpServletRequest.getHeader("satoken"));
        return Result.success(200, "返回", administrateurMapper.sucinfo(s));
    }

    /**
     * @param
     * @return 同意请假，往打卡表插入数据，-1代表请假，就不需要进行打卡了，还有一个连续几天内设置学生istrue为-1(打卡表),审批表0待审核1通过2拒绝
     * @throws Exception
     */
    @RequestMapping("/succdem")
    public Result succdem(@RequestBody Editdto editdto) throws Exception {
        Demander demander = DemanderService.getOne(new QueryWrapper<Demander>().eq("id", editdto.getUserid()));
        List<Cheeck> cheeckList = new ArrayList<>();
        Stustatus stustatus = new Stustatus();
        stustatus.setIsleave(0);
        stustatus.setStudentid(demander.getStudentid());
        stustatusService.updateById(stustatus);
        demander.setIstrue(1);
        LocalDate localDate = LocalDate.now();
        LocalTime localTime = LocalTime.now();
        DateTimeFormatter fmt = DateTimeFormatter.ofPattern("yyyy-MM-dd");
        String s = demander.getEntime();
        String s1 = demander.getSttime();
        List<String> list = (List<String>) Rqizhuanhuan.findEveryDay(s1, s).get("info");
        int k = (int) Rqizhuanhuan.findEveryDay(s1, s).get("vaule");
        for (int i = 0; i <= k; i++) {
            Cheeck cheeck = new Cheeck();
            cheeck.setStudentid(demander.getStudentid());
            cheeck.setIstrue("-1");
            cheeck.setTtime(localTime);
            cheeck.setQdate(LocalDate.parse(list.get(i)));
            cheeck.setTime(localDate);
            cheeckList.add(cheeck);
        }
        DemanderService.updateById(demander);
        return Result.success(200, "成功", cheeckService.saveBatch(cheeckList));
    }

    /**
     * @param
     * @return 拒绝当前请假，返回由code判定
     */
    @RequestMapping("/noleave")
    public Result noleave(@RequestBody Editdto editdto) {
        Demander demander = DemanderService.getOne(new QueryWrapper<Demander>().eq("id", editdto.getUserid()));
        demander.setIstrue(2);
        Stustatus stustatus = new Stustatus();
        stustatus.setIsleave(0);
        stustatus.setStudentid(demander.getStudentid());
        stustatusService.updateById(stustatus);
        boolean flag = DemanderService.updateById(demander);
        if (flag) {
            return Result.success(200, "成功", null);
        } else {
            return Result.fail(400, "失败", null);
        }
    }

    /**
     * @param edpassDto
     * @return 记得这个要验证一下之前的密码，这里我没写
     */
    @RequestMapping("/edpassword")
    public Result edpassword(EdpassDto edpassDto) {
        Administrateur administrateur = new Administrateur();
        String secret = SecretUtil.secret;
        administrateur.setPassword(SecureUtil.hmacSha1(secret).digestHex(edpassDto.getPassword()));
        administrateur.setId(edpassDto.getId());
        boolean flag = administrateurService.updateById(administrateur);
        if (flag != true) {
            return Result.fail(405, "密码修改失败", null);
        } else {
            return Result.success(200, "密码修改成功", null);
        }
    }

    @RequestMapping("/test")
    public Result test() {
        Integer s = 123456;
        Administrateur administrateur = new Administrateur();
        administrateur.setName("adminsitorfwerfwer");
        administrateur.setAdmid(256);
        administrateur.setPid(2);
        administrateur.setPassword(SecureUtil.hmacSha1(secret).digestHex(String.valueOf(s)));
        administrateurService.save(administrateur);
        return Result.success(200, "成功", null);
    }

    @RequestMapping("/test2")
    public Result test2() {
        Administrateur administrateur1 = administrateurService.getOne(new QueryWrapper<Administrateur>().eq(
                "admid", 256
        ));
        return Result.success(200, "成功", administrateur1);
    }

    @RequestMapping("/login")
    public Result login(@RequestBody Administrateur administrateur) {
        Administrateur administrateur1 = administrateurService.getOne(new QueryWrapper<Administrateur>().eq(
                "admid", Integer.valueOf(administrateur.getAdmid())
        ));
        if (administrateur1 == null) {
            return Result.fail(401, "用户不存在", null);
        }

        boolean flag = administrateur1.getPassword().equals(
                SecureUtil.hmacSha1(secret)
                        .digestHex(administrateur.getPassword())
        );
        if (flag) {
            StpUtil.login(administrateur.getAdmid());
            System.out.println(StpUtil.getTokenValue());
            Map<String, Object> objectMap = new HashMap<>(2);
            objectMap.put("token", StpUtil.getTokenInfo());
            administrateur.setPassword(null);
            objectMap.put("administrateur", administrateur1);
            return Result.success(200, "登陆成功", objectMap);
        } else {
            return Result.fail(400, "密码错误", null);
        }
    }
}
